package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;

@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /* HttpSession session = request.getSession();*/
        //  这里改为用redis获取用户信息
        String token = request.getHeader("authorization");
        String tokenKey = LOGIN_USER_KEY + token ;
        /*log.debug("LoginInterceptor中的" + token);*/
        if(token == null){
            return true;
        }
        Map<Object, Object> entriesMap = stringRedisTemplate.opsForHash().entries(tokenKey);
        /*UserDTO user = (UserDTO)session.getAttribute("user");*/
        if(entriesMap.isEmpty()){

            return true;
        }
        UserDTO userDTO = BeanUtil.fillBeanWithMap(entriesMap, new UserDTO(), false);
        //  如果用户存在，重新设置redis的过期时长
        stringRedisTemplate.expire(tokenKey,30, TimeUnit.MINUTES);
        //如果用户存在，把他放在ThreadLocal当中
        UserHolder.saveUser(userDTO);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        UserHolder.removeUser();
    }
}
